#!/usr/bin/python


#######################

class CommentWriter:

	def __init__(self):
		self.functions = []
		self.currentFunction = -1
		
	def addFunction(self, name):
		newNode = Function(name)
		self.functions.append(newNode)
		self.currentFunction = self.functions[-1] 

	def addProperty(self, name, value, functionName = "", subsetName = ""):
		selection = self.findFunction(functionName)
		selection.addProperty(name, value, subsetName)

	def addSubset(self, name, functionName = ""):
		selection = self.findFunction(functionName)
		selection.addSubset(name)
	
	def findFunction(self, name):
		if (name == ""):
			selection = self.currentFunction
		else:
			for function in self.functions:
				if (function.name == name):
					selection = function
					break
		if (not selection or selection == -1):
			print ('Sorry, function %s not found') % name
			return
		return selection	
	

	def writeXML(self):
		output = "<f>"
		for each in self.functions:
			output += "<" + each.name  + ">"
			subsetNames = each.getSubsets()
			for name in subsetNames:
				output += "<" + name + ">"
				for pair in each.getProperties(name):
					output += "<" + str(pair[0]) + ">" + str(pair[1]) + "</" + str(pair[0]) + ">"
				output += "</" + name + ">" 
			output += "</" + each.name + ">"
		output += "</f>"
		return output

class Function:
	
	def __init__(self, name):
		self.name = name
		self.subsets = []
		self.currentSubset = -1

	def addSubset(self, name):
		if name == "":
			print "Error, no name provided"
			return
		self.subsets.append([name, {}])
		self.currentSubset = self.subsets[-1]

	def addProperty(self, name, value, subsetName = ""):
		subset = self.findSubset(subsetName)
		if (not subset):
			return
		subset[1][name] = value

	def getSubsets(self):
		subsets = []
		for each in self.subsets:
			subsets.append(each[0])
		return subsets

	def getProperties(self, subsetName):
		subset = self.findSubset(subsetName)
		if (not subset):
			return
		properties = subset[1]
                keys = properties.keys()
                keys.sort()
                sorted = []
                for key in keys:
                        sorted.append((key, properties[key]))
                return sorted
	
	def findSubset(self, subsetName):
		subset = ["",{}]
		if (subsetName == ""):
			subset = self.currentSubset 		
		elif (subsetName == self.currentSubset[0]):
			subset = self.currentSubset
		else:
			for each in self.subsets:
				if each[0] == subsetName:
					subset = each
					break
		if (subset[0] == ""):
			print "Error, subset %s not found" % subsetName
			return
		return subset							


